const config = require("config.js"); //配置文件
/****
 * ajax_curl,同后台进行数据交互函数
 * url请求地址；data：数据；cb：回调函数；
 * posttype：get 或者post
 * nojson：0代表json格式数据，1代表key=>value格式数据
 * json数据后台需要使用file_get_contents("php://input")接收
 * key=>value格式数据，后台使用$_POST接收
 ****/

function ajax_curl(url, data, cb, posttype = "get") {
  var method_type = posttype.toUpperCase();

  if (method_type == "POST") {
    var headerset = "application/x-www-form-urlencoded";
  } else {
    var headerset = "application/json";
  }

  if (!data) {
    data = {};
  }
  wx.request({
    url: url,
    data: data,
    method: method_type,
    timeout: 60000,
    header: {
      "Content-Type": headerset,
    },
    success: function (res) {
      if (res.data.code == 0) {
        typeof cb == "function" && cb(res.data.data);
      } else {
        wx.showToast({
          title: res.data.msg ? res.data.msg : "接口异常",
          icon: "none",
          duration: 2000,
        });
        var logData = {};
        logData.url = url;
        logData.data = JSON.stringify(data);
        logData.res = JSON.stringify(res);
      }
    },
    fail: function (res) {
      console.log(res);
      var logData = {};
      logData.url = url;
      logData.data = JSON.stringify(data);
      logData.res = JSON.stringify(res);
    },
  });
}

function rel_login(cb) {
  wx.login({
    success: function (res) {
      if (res.code) {
        var param = {
          code: res.code,
        };
        console.log('url', config.UserOpenid)
        ajax_curl(config.UserOpenid, param, function (result) {
          var userInfo = result;
          console.log(111, result)
          wx.setStorageSync("userInfo", userInfo);
          typeof cb == "function" && cb(userInfo);
        }, "post");
      } else {
        console.log("login获取code失败！", res);
      }
    },
    fail: function (res) {
      console.log("login执行失败！", res);
    },
  });
}
/****
 * 登录接口
 * cb：回调函数；
 ****/

function login(cb) {
  /**检查session是否失效**/
  wx.checkSession({
    success: function () {
      var userInfo = wx.getStorageSync("userInfo");

      if (userInfo) {
        typeof cb == "function" && cb(userInfo);
      } else {
        rel_login(cb);
      }
    },
    fail: function () {
      rel_login(cb); //重新登录
    },
  });
}

function check_login(cb, page_login_state = "login_page") {
  /**检查session是否失效**/
  wx.checkSession({
    success: (res) => {
      var userInfo = wx.getStorageSync("userInfo");
      if (!userInfo || !userInfo.openid) {
        wx_login(cb, page_login_state)
      } else {
        typeof cb == "function" && cb(userInfo);
      }
    },
    fail: () => {
      wx_login(cb, page_login_state);
    },
  });
}

function wx_login(cb, page_login_state) {
  wx.login({
    success: (res) => {
      if (res.code) {
        ajax_curl(
          config.UserOpenid, {
            code: res.code,
          },
          function (userInfo) {
            console.log('登录', userInfo)
            wx.setStorageSync("userInfo", userInfo);
            typeof cb == "function" && cb(userInfo);
          },
          "post"
        );
      } else {
        console.log("login获取code失败！", res);
      }
    },
    fail: function (res) {
      console.log("login执行失败！", res);
    },
  });
}
/****
 * 普通的获取后台数据接口,同后台进行数据交互函数
 *会自动在param 新增用户mc_session
 * url请求地址；param：数据；method：方法  func_success回调函数；
 ****/

function getData_user(url, param = {}, method, func_success) {
  var req = function () {
    var userInfo = wx.getStorageSync("userInfo") || {};
    if (userInfo && userInfo.openid) {
      param.openid = userInfo.openid;
    }

    ajax_curl(url, param, func_success, method);
  };

  check_login(req, "login_info");
}

/****
 * 普通的获取后台数据接口,同后台进行数据交互函数
 * url请求地址；param：数据；method：方法  func_success回调函数；
 ****/

function getData(url, param = {}, method, func_success) {
  ajax_curl(url, param, func_success, method);
}

function getlistdata_user(that, url, param = {}, isrefresh = 0) {
  check_login(function (userinfo) {
    param.openid = userinfo.openid;
    getlistdata(that, url, param, isrefresh);
  }, "login_info");
}
/****
 * 普通的获取后台数据接口,同后台进行数据交互函数，带有分页功能
 * url请求地址；param：数据；method：方法  func_success回调函数；isrefresh代表是否是下拉刷新
 ****/

function getlistdata(that, url, param = {}, isrefresh = 0) {
  if (that.data.isnodata || that.data.isajax) {
    return false;
  }

  if (that.data.currentNo == 1) {
    wx.showLoading({
      title: "加载中...",
      mask: true,
    });
  }

  that.setData({
    isajax: true,
  });
  param.page = that.data.currentNo;
  param.limit = that.data.pagesize;
  var data_key = "listarr[" + that.data.currentNo + "]";
  getData(url, param, "post", function (res) {
    if (that.data.currentNo == 1) {
      wx.hideLoading();
    }

    if (res.list.length < that.data.pagesize) {
      that.setData({
        isnodata: true,
      });
    }

    that.setData({
      currentNo: that.data.currentNo + 1,
      [data_key]: res,
      isajax: false,
      common_loaded: 1,
    });
    if (isrefresh) {
      wx.stopPullDownRefresh();
    }
    if (that.data.callbackFlag) {
      let callbackAfterRefresh = that.callbackAfterRefresh;
      typeof callbackAfterRefresh == "function" && callbackAfterRefresh();
      that.setData({
        callbackFlag: false,
      });
    }
  });
}

function changelistdata_user(that, url, param = {}, isrefresh = 0) {
  check_login(function (userinfo) {
    param.openid = userinfo.openid;
    changelistdata(that, url, param, isrefresh);
  }, "login_info");
}
/****
 * 普通的获取后台数据接口,同后台进行数据交互函数，带有分页功能，用户第一次取数据或者刷新条件
 * url请求地址；param：数据；method：方法  func_success回调函数；isrefresh代表是否是下拉刷新
 ****/

function changelistdata(that, url, param = {}, isrefresh = 0) {
  that.setData({
    currentNo: 1,
    listarr: [],
    isnodata: false,
    isajax: false,
  });
  getlistdata(that, url, param, isrefresh);
}
/**
 * todo 唤起手机号登录界面
 * cb 登录后的回调方法
 * allCb 不管成功或失败都执行的回调
 * noTip 没有提示
 */

const getPhoneNumber = function (event, cb, hasTip, allCb, noTip) {
  if (event.detail.errMsg == "getPhoneNumber:ok") {
    var param = {
      iv: encodeURIComponent(event.detail.iv),
      encryptedData: encodeURIComponent(event.detail.encryptedData),
      openid: wx.getStorageSync("userInfo").openid,
    };
    console.log("event", event);
    wx.showLoading({
      title: '授权中...',
      mask: true
    });
    getData(config.UserPhone, param, "POST", function (res) {
      wx.hideLoading();
      if (res) {
        mySetStorageSyncInfo(res);
        if (typeof allCb == "function") allCb(event);
        typeof cb == "function" && cb(event, res);
      } else {
        if (typeof allCb == "function") {
          allCb(event);
          return;
        }
        if (!noTip) showToast("text", res.msg);
      }
    });
  } else {
    if (typeof allCb == "function") {
      allCb(event);
      return;
    }
    console.error("error", event);
    let tip = "授权失败";
    if (!!hasTip) {
      tip = hasTip;
    }
    if (!noTip) showToast("text", tip);
  }
};

module.exports = {
  ajax_curl,
  login,
  config,
  getData,
  getData_user,
  getlistdata,
  changelistdata,
  getlistdata_user,
  changelistdata_user,
  check_login,
  getPhoneNumber,
  rel_login,
};